package org.github.rayson517.easyplatform.message.handler;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Predicate;

import org.github.rayson517.easyplatform.message.constant.SystemConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;

/**
 * 创建连接 握手事件
 * @author Administrator
 *
 */
@Component
public class ConnectHandler {
	
	private static final Logger log = LoggerFactory.getLogger(ConnectHandler.class);
	
	@Autowired
	SocketIOServer server;
	
	/**
	 * 存储连接的客户端
	 */
	private static final Map<String, List<SocketIOClient>> clients = new ConcurrentHashMap<>();
	
	@OnConnect
	public void onConnect(SocketIOClient client) {
		System.out.println(server.getAllNamespaces().size());
		System.out.println(client.getNamespace().getName());
		String appId = client.getHandshakeData().getSingleUrlParam("appId"); // appID
		String appKey = client.getHandshakeData().getSingleUrlParam("appKey"); // appKey
		server.addNamespace("/"+appId);
		// 从数据库查询 是否一致 此处我是存储在config.properties里面
		if(SystemConstant.SOCKETIO_APPID.equals(appId) && SystemConstant.SOCKETIO_APPKEY.equals(appKey)){ // 校验appId 和 appKey
			log.debug(">>>>>校验成功!" + appId);
			List<SocketIOClient> list = clients.get(appId);
			System.out.println(list);
			if(list == null){
				list = Collections.synchronizedList(new ArrayList<>());
				list.add(client);
				clients.put(appId, list);
			}else{
				boolean flag = false;
				for(SocketIOClient t : list){
					if(t.getSessionId().equals(client.getSessionId())){
						flag = true;
						break;
					}
				}
				if(!flag){ // false
					list.add(client);
				}
			}
		}else{
			client.disconnect();
		}
		
		log.debug(">>>>>添加成功!"+clients.get(appId).size());
	}
	
	@OnDisconnect
	public void onDisconnect(SocketIOClient client){
		String appId = client.getHandshakeData().getSingleUrlParam("appId"); // appID
		String appKey = client.getHandshakeData().getSingleUrlParam("appKey"); // appKey
		// 从数据库查询 是否一致 此处我是存储在config.properties里面
		if(SystemConstant.SOCKETIO_APPID.equals(appId) && SystemConstant.SOCKETIO_APPKEY.equals(appKey)){ // 校验appId 和 appKey
			clients.get(appId).remove(client);
			log.debug(">>>>>移除成功!"+clients.get(appId).size());
		}
		client.disconnect();
	}
}
